﻿using Estsh.Core.Model.EnumUtil;
using Estsh.Core.Models;
using Estsh.Core.Quartz.BaseService;
using Estsh.Core.Util;
using Estsh.Core.Wms.IRepositories;

namespace Estsh.Core.Wms.Jobs
{
    /// <summary>
    /// 针对MES发送过来的成品发运信息，WMS自动触发成品发运处理
    /// </summary>
    public class JisShipJob : IJobService
    {
        private readonly IJisShippingRepository repository;
        private readonly IStockRepository stockRepository;


        public JisShipJob(IJisShippingRepository _repository, 
            IStockRepository _stockRepository)
        {
            this.repository = _repository;
            this.stockRepository = _stockRepository;

        }

        public string ExecuteService(string parameter)
        {
            try
            {
                List<MesWmsJisShipping> mesWmsJis = repository.GetFinishedShippedInfo();
                if (mesWmsJis.Count > 0)
                {
                    repository.InsertFinishedShippedInfo(mesWmsJis);// "待处理的成品发运JIS！";
                }

                List<MesJisShipping> jisShips = repository.GetJisShippingInfo();
                if (jisShips.Count <= 0)
                {
                    return "没有待JIS发运的数据！";
                }

                foreach (var jisShip in jisShips)
                {
                    var cartonInfo = stockRepository.GetCartonInfo(jisShip.SerialNumber);
                    if (cartonInfo == null)
                    {
                        repository.UpdateJisShippingInfo(jisShip, MesEnumUtil.JisShipStatus.EXCEPTION, "此成品还未入库！");
                        continue;
                    }
                    if (cartonInfo.Status == (int)WmsEnumUtil.StockStatus.SHIPPED)
                    {
                        repository.UpdateJisShippingInfo(jisShip, MesEnumUtil.JisShipStatus.EXCEPTION, "此成品已发运，不能重复发运！");
                        continue;
                    }
                    if (cartonInfo.Status != (int)WmsEnumUtil.StockStatus.INSTOCKED)
                    {
                        repository.UpdateJisShippingInfo(jisShip, MesEnumUtil.JisShipStatus.EXCEPTION, "此成品库存状态不是在库状态！");
                        continue;
                    }

                    repository.DoJisShip(jisShip, cartonInfo);
                }
                return "JIS发运成功！";

            }
            catch (Exception ex) 
            {
                LogHelper.Error("JIS发运错误！" + ex);
                return "JIS发运错误！" + ex.Message;
            }
            
        }
    }
}
